package sk.stuba.fiit.team14.game.mapengine;

import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.opengl.texture.region.TextureRegion;

public class Component extends Sprite {
	
	int CELLS_HORIZONTAL = 15;
	int CELLS_VERTICAL = 10;
	
	static int CELL_WIDTH = 32;
	static int CELL_HEIGHT = CELL_WIDTH;

	int mCellX;
	int mCellY;
	
	public boolean isMovable;
	public boolean isControllable;
	public boolean isThrowable;
	public boolean isDestructible;
	
	protected int	mDirection;
	
	protected long lastMoved;
	
	public Component(final int pCellX, final int pCellY, final int pWidth, final int pHeight, final TextureRegion pTextureRegion) {
		super(pCellX * CELL_WIDTH, pCellY * CELL_HEIGHT, pWidth, pHeight, pTextureRegion);
		mCellX = pCellX;
		mCellY = pCellY;
		
		isMovable			= false;
		isControllable		= false;
		isThrowable			= false;
		isDestructible		= false;
	}
	
	public int getCellX() {
		return mCellX;
	}
	public int getCellY() {
		return mCellY;
	}

	public void setCell(final Component pCellEntity) {
		this.setCell(pCellEntity.getCellX(), pCellEntity.getCellY());
	}
	
	public boolean setCell(final int pCellX, final int pCellY) {
		lastMoved = System.currentTimeMillis();
		
		boolean moved = true;
		
		mCellX = pCellX;
		mCellY = pCellY;
		
		if (mCellX < 0) {
			mCellX = 0;
			moved = false;
		} else if (mCellX >= CELLS_HORIZONTAL) {
			mCellX = CELLS_HORIZONTAL - 1;
			moved = false;
		}
		
		if (mCellY < 0) {
			mCellY = 0;
			moved = false;
		} else if (mCellY >= CELLS_VERTICAL) {
			mCellY = CELLS_VERTICAL - 1;
			moved = false;
		}
		
		setPosition(mCellX * CELL_WIDTH, mCellY * CELL_HEIGHT);
		
		return moved;
	}

	public boolean isInSameCell(int pCellX, int pCellY) {
		return ((mCellX == pCellX) && (mCellY == pCellY));
	}
	
	public boolean isInSameCell(final Component pCellEntity) {
		return ((mCellX == pCellEntity.getCellX()) && (mCellY == pCellEntity.getCellY()));
	}
	
	public void move(int pDirection) {
		/*
		 * 0 stop
		 * 1 right
		 * 2 down
		 * 3 left
		 * 4 top
		 */
		mDirection = pDirection;
	}
	
	public int getDirection() {
		return mDirection;
	}
	
	public int getNextX() {
		switch (mDirection) {
		case 1: return mCellX + 1;
		case 3: return mCellX - 1;
		default :
			return mCellX; 
		}
	}
	
	public int getNextY() {
		switch (mDirection) {
		case 2: return mCellY + 1;
		case 4: return mCellY - 1;
		default :
			return mCellY; 
		}
	}
	
	public boolean wantMove() {
		if (System.currentTimeMillis() - lastMoved < 500) return false;
		return mDirection != 0;
	}
}
